﻿using UnityEngine;
using System.Collections;

public class Blaster : MonoBehaviour {

    public GameObject Fab;
    public float Rof = 1.0f;

    Camera Cam;
    Vector2 XBnds;
	void Start () {
	    Cam = Camera.main;
        var sz = GetComponent<BoxCollider>().size; sz.Scale(transform.lossyScale);
        XBnds.x = transform.position.x - sz.x*0.5f; XBnds.y = XBnds.x+sz.x;
        
	}
	
    float Next = 0;

    float Fury = -9999.0f;
	
	void Update () {
      //  Debug.Log( "  "+Cam.transform.position.x+"  "+ XBnds);
        if(Cam.transform.position.x > XBnds.x && Cam.transform.position.x < XBnds.y) {

            if( Fury < Time.time-10.0f )Fury = Time.time + 15.0f;
            if(Next < Time.time) {
                var ray = Cam.ScreenPointToRay( new Vector3(Screen.width*1.1f, Random.Range(0.1f,0.9f)*Screen.height, 0 ) );
                var p = ray.GetPoint( -ray.origin.z / Vector3.Dot(ray.direction,Vector3.forward));
                //var p = Cam.ScreenToWorldPoint( new Vector3(Screen.width*1.1f, Random.Range(0.1f,0.9f)*Screen.height, 0 ));
                
                p.z = -0.8f;
                Instantiate( Fab, p, Quaternion.Euler( new Vector3(0,0,90.0f+ Random.Range(-5.0f,5.0f) )));

                Next = Rof *Random.Range(0.5f,1.5f);
                if( Fury < Time.time ) Next *=0.1f; 
                Next += Time.time;
            }
        }
	}
}
